from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosBill, collectionBillList
from app.globals.publicMethod import globalGetNowTime
from datetime import datetime
import random

def createOrder(diningNo, stallNo, billId, deviceNo, skj130OrderTime, appLocalOrderId,
        skj130GatewayNo, skj130PosNo, orderAmount, 
        chargeAmount, cardQrCodeNum, billState, 
        payType, dishList, thirdOrderNo, billType, operator):
    '''
    订单存储
    '''
    try:
        mg_client = get_mongo_client()
        # 为唯一判断条件，如果已存在则丢弃，并返回成功
        cond = {'appLocalOrderId': appLocalOrderId}
        collection = mg_client[dbSynPosBill][collectionBillList]
        res = collection.find_one(cond)
        # 如果已存在则丢弃
        if res is not None:
            return None   
    
        bill_130Time = datetime.strptime(skj130OrderTime, "%Y-%m-%d %H:%M:%S")
        # billId = bill_130Time.strftime("%Y%m%d%H%M%S")
        # skj130No = 0
        # if skj130PosNo.isdigit() is True:
        #     skj130No = int(skj130PosNo)
        # else:
        #     skj130No = random.randint(1, 999)
        # endNo = random.randint(1000, 9999)
        # billId = f'{billId}{skj130No}{endNo}'
        data = {
            'diningNo': diningNo,
            'stallNo': stallNo,
            'billId': billId,
            'deviceNo': deviceNo,
            'thirdOrderNo': thirdOrderNo,
            'skj130OrderTime': bill_130Time,
            'appLocalOrderId': appLocalOrderId,
            'skj130GatewayNo': skj130GatewayNo,
            'skj130PosNo': skj130PosNo,
            'createTime': globalGetNowTime(),
            'orderAmount': orderAmount,
            'chargeAmount': chargeAmount,
            'cardQrCodeNum': cardQrCodeNum,
            'billState': billState,
            'payType': payType,
            'dishList': dishList,
            'billType': billType,
            'operator': operator
        }
        return collection.insert_one(data)
    except Exception as e:
        raise ErrMongoClient.data(str(e))   